package com.jfinal.demo.web.validator;

import com.jfinal.core.Controller;
import com.jfinal.demo.web.controller.LoginController;
import com.jfinal.ext.render.CaptchaRender;
import com.jfinal.kit.StrKit;
import com.jfinal.validate.Validator;

/**
 * 登录表单验证
 * 
 * @author Administrator
 * 
 */
public class LoginValidator extends Validator {

	@Override
	protected void validate(Controller c) {
		String username = c.getPara("username");
		String password = c.getPara("password");
		String kaptchaCode = c.getPara("kaptchaCode");

		// 验证空
		validateRequiredString("username", "usernameMsg", "用户名不能为空");
		validateRequiredString("password", "passwordMsg", "密码不能为空");
		validateRequiredString("kaptchaCode", "kaptchaCodeMsg", "验证码不能为空！");

		// 验证正确性
		if (StrKit.notBlank(username) && !"admin".equals(username)) {
			addError("usernameMsg", "用户名不正确！");
		}
		if (StrKit.notBlank(password) && !"123456".equals(password)) {
			addError("passwprd", "密码不正确！");
		}
		if (StrKit.notNull(kaptchaCode)
				&& !CaptchaRender.validate(c, kaptchaCode,
						LoginController.RANDOM_CODE_KEY)) {
			addError("kaptchaCodeMsg", "验证码不正确！");
		}
	}

	@Override
	protected void handleError(Controller c) {
		c.keepPara("username");
		c.render("index.jsp");
	}

}
